package com.nicolasprof.profgallery.effects {
	import gs.TweenLite;

	import com.nicolasprof.profgallery.Engine;
	import com.nicolasprof.profgallery.effects.ParticleEffect;

	import flash.display.Bitmap;
	import flash.display.Shape;
	import flash.display.Sprite;

	/**
	 * @author Nicolas Prof
	 */
	public class WiperEffect extends ParticleEffect {
		public function WiperEffect() {
			super();
		}
		override public function build(...$layers) : void {
			var config: XML = getConfig();
			var countX : int = Math.max(config.@countX, 1);
			var countY : int = Math.max(config.@countY, 1);
			var bitmap : Bitmap = $layers[0];
			var width : Number = bitmap.width;
			var height : Number = bitmap.height;
			var mask : Sprite = $layers[1];

			var sqWidth : int = Math.ceil(width / countX);
			var sqHeight : int = Math.ceil(height / countY);
			var bigSide: int = Math.max(sqWidth, sqHeight);
			var radius : int = bigSide / Math.sqrt(2);
			
			var i: int, j:int, k:int;
			var delayFactor: Number;
			var xmlDelay: Number = config.@delay;
			var xmlTime: Number = config.@time;
			var len: int = countX * countY;
			var posX: Number;
			var posY: Number;
			var offsetX: Number = config.@moveX;
			var offsetY: Number = config.@moveY;
			
			mask.cacheAsBitmap = true;
			bitmap.cacheAsBitmap = true;
			bitmap.mask = mask;
			parseEase();
			
			for(j =0; j < countY; j++){
				for(i=0; i < countX;i++){
					k++;
					
					var circle : Shape = getCircle(radius);
					
					mask.addChild(circle);
					
					circle.x = posX = sqWidth * 0.5 + i * sqWidth;
					circle.y = posY = sqHeight * 0.5 + j * sqHeight;	
					circle.x += offsetX;
					circle.y += offsetY;
					circle.scaleX = circle.scaleY = 0;
					circle.alpha = 0;
					delayFactor = _ease(k, 0, xmlDelay, len);
					TweenLite.to(circle, xmlTime, {scaleX:1, scaleY:1, alpha:1, x: posX, y : posY, delay: delayFactor, overwrite:0});
				}
			}
		}

		private function getCircle($r: int) : Shape {
			var circle : Shape = new Shape();
			
			circle.graphics.beginFill(0xFF0000);
			circle.graphics.drawCircle(0, 0, $r);
			circle.graphics.endFill();
			
			return circle;
		}
		override protected function getConfig() : XML {
			var config : XML = Engine.CONFIG_XML;
			return config.effects.wiper[0];
		}
	}
}
